﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Deployment.Application;
using System.IO;
using System.Web;
using RemoteTestRunner.BusinessLogic.Properties;

namespace RemoteTestRunner.BusinessLogic
{
    public static class RtrSettings
    {
        public static event EventHandler SettingsUpdated;

        public static void Save()
        {
            Settings.Default.DefaultSettings = false;
            Settings.Default.Save();
            if (SettingsUpdated != null)
            {
                SettingsUpdated(null, EventArgs.Empty);
            }
        }

        #region Properties

        private static readonly bool _userSettings;

        static RtrSettings()
        {
            // test the settings base to see if user scope is available
            try
            {
                // If an exception occurs on this call then the settings will be pulled from the config file instead of the settings object.
                var defaultSettings = Settings.Default.DefaultSettings;
                _userSettings = true;

                if (defaultSettings)
                {
                    UpdateSettingsForClickOnceUrlParameters();
                }
            }
            catch (ConfigurationErrorsException)
            {
                // RTR settings are running within the service, not the ClickOnce app.
                _userSettings = false;
            }
        }

        public static string DataPath
        {
            get
            {
                if (_userSettings)
                {
                    return Path.GetFullPath(Settings.Default.DataPath);
                }
                else
                {
                    return ConfigurationManager.AppSettings["DataPath"];
                }
            }

            set { Settings.Default.DataPath = value; }
        }

        public static string WorkingFolder
        {
            get
            {
                string path;
                if (_userSettings)
                {
                    path = Path.GetFullPath(Settings.Default.WorkingFolder);
                }
                else
                {
                    path = ConfigurationManager.AppSettings["WorkingFolder"];
                }

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                return path;
            }

            set { Settings.Default.WorkingFolder = value; }
        }

        public static string MSTestPath
        {
            get
            {
                if (_userSettings)
                {
                    return Settings.Default.MSTestPath;
                }
                else
                {
                    return ConfigurationManager.AppSettings["MSTestPath"];
                }
            }

            set { Settings.Default.MSTestPath = value; }
        }

        public static int TestTimeoutSeconds
        {
            get
            {
                if (_userSettings)
                {
                    return Settings.Default.TestTimeoutSeconds;
                }
                else
                {
                    return int.Parse(ConfigurationManager.AppSettings["TestTimeoutSeconds"]);
                }
            }

            set { Settings.Default.TestTimeoutSeconds = value; }
        }

        public static bool UseRunnerService
        {
            get
            {
                if (_userSettings)
                {
                    return Settings.Default.UseRunnerService;
                }
                else
                {
                    return bool.Parse(ConfigurationManager.AppSettings["UseRunnerService"]);
                }
            }
            set { Settings.Default.UseRunnerService = value; }
        }

        public static bool FilterTests
        {
            get
            {
                if (_userSettings)
                {
                    return Settings.Default.FilterTests;
                }
                else
                {
                    return bool.Parse(ConfigurationManager.AppSettings["FilterTests"]);
                }
            }
            set { Settings.Default.FilterTests = value; }
        }

        public static string RunnerServiceUrl
        {
            get
            {
                if (_userSettings)
                {
                    return Settings.Default.RunnerServiceUrl;
                }
                else
                {
                    return ConfigurationManager.AppSettings["RunnerServiceUrl"];
                }
            }
            set { Settings.Default.RunnerServiceUrl = value; }
        }

        private static NameValueCollection GetQueryStringParameters()
        {
            var nameValueTable = new NameValueCollection();

            if (ApplicationDeployment.IsNetworkDeployed)
            {
                var queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;

                nameValueTable = HttpUtility.ParseQueryString(queryString);
            }

            return (nameValueTable);
        }

        private static void UpdateSettingsForClickOnceUrlParameters()
        {
            var parameters = GetQueryStringParameters();

            if (parameters.Count > 0)
            {
                bool useRunnerService;
                if (bool.TryParse(parameters.Get("UseRunnerService"), out useRunnerService))
                {
                    UseRunnerService = useRunnerService;
                }

                if (!string.IsNullOrEmpty(parameters.Get("DataPath")))
                {
                    DataPath = parameters.Get("DataPath");
                }

                if (!string.IsNullOrEmpty(parameters.Get("RunnerServiceUrl")))
                {
                    RunnerServiceUrl = parameters.Get("RunnerServiceUrl");
                }
            }
        }

        #endregion
    }
}